package com.xqnode.kafka.producer;

import cn.hutool.core.date.DateUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xqnode.kafka.producer.beans.Message;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Component
public class MyProducer {

    private final KafkaTemplate<String, String> kafkaTemplate;

    //构造器方式注入 kafkaTemplate
    public MyProducer(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    private final Gson gson = new GsonBuilder().create();

    public void send(String msg) {
        for (int i = 0; i < 1000; i++) {
            Message message = new Message();

            message.setId(Long.valueOf(i + ""));
            message.setMsg(msg);
            message.setTime(DateUtil.now());
            //对 topic = hello2 的发送消息
            kafkaTemplate.send("topic-spring-1", gson.toJson(message));
        }
    }

}
